package com.example.lib_common

import android.content.Context
import android.os.SystemClock
import android.util.TypedValue
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.lib_common.base.BaseApplication
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import me.jessyan.autosize.utils.AutoSizeUtils

//在指定的生命周期状态下（默认是 RESUMED）开始收集 Flow
//当生命周期低于指定状态时自动取消收集
//使用 collectLatest 确保只处理最新的值
fun <T> Flow<T>.observeWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    minState: Lifecycle.State = Lifecycle.State.RESUMED,
    action:suspend (T) -> Unit
)
//lifecycleOwner: 生命周期拥有者（如 Activity/Fragment）
//minState: 最小生命周期状态（默认为 RESUMED）
//action: 处理每个值的挂起函数
: Job = lifecycleOwner.lifecycleScope.launch {
    //使用 lifecycleScope 启动协程
    //通过 repeatOnLifecycle 实现生命周期感知
    //使用 collectLatest 而不是 collect 以避免处理过时数据
    lifecycleOwner.repeatOnLifecycle(minState){
        collectLatest {
            action.invoke(it)
        }
    }
}

//获取属性值
fun getAttrValue(context: Context, attrId: Int): Int {
    val typedValue = TypedValue()
    context.theme.resolveAttribute(attrId, typedValue, true)
    return typedValue.resourceId
}

val appContext: Context
    get() = BaseApplication.instance

//dp转px 按照dp单位绘制，根据手机dpi屏幕像素密码绘制对应px
val Int.dp: Int
    get() = AutoSizeUtils.dp2px(appContext, this.toFloat())
val Float.dp: Float
    get() = AutoSizeUtils.dp2px(appContext, this).toFloat()

//按键消抖
fun View.clickFlow() = callbackFlow {
    setOnClickListener {
        trySend(Unit).onFailure { e -> e?.printStackTrace() }
    }
    awaitClose { setOnClickListener(null) }
}

//阿里云-获取视频首帧图片
fun getAliOSSVideoImage(videoUrl: String): String {
    return "$videoUrl&x-oss-process=video/snapshot,t_1,f_jpg,ar_auto"
}

fun <T> Flow<T>.throttleFirst(thresholdMillis: Long) = flow {
    var lastTime = 0L
    collect { upstream ->
        val currentTime = SystemClock.elapsedRealtime()
        if (currentTime - lastTime >= thresholdMillis) {
            lastTime = currentTime
            emit(upstream)
        }
    }
}
/**
 * 处理url参数 转成 map  xxx=xxx&xxx=xxx
 */
fun getUrlParams(param: String): Map<String, Any?> {
    val map: MutableMap<String, Any> = HashMap(0)
    if (param.isBlank()) {
        return map
    }
    val params = param.split("&".toRegex()).toTypedArray()
    for (i in params.indices) {
        val p = params[i].split("=".toRegex()).toTypedArray()
        if (p.size == 2) {
            map[p[0]] = p[1]
        }
    }
    return map
}


